package client.service;

import java.io.DataInputStream;

import java.io.DataOutputStream;
import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Hashtable;

import client.FriendListManager;
import com.google.gson.Gson;

import client.view.FriendList;
import javafx.application.Platform;
import javafx.scene.control.Alert;
import model.*;
import client.StreamCloser;

public class UpdateFriendList implements Runnable{

    private DataOutputStream output;
    private DataInputStream input;
    private int useraccount;
	private boolean isrunning = true;
	private StreamCloser s;
    private Hashtable<Integer, String> addmes;
	
	Type hashtableType = new ParameterizedType() {
        public Type[] getActualTypeArguments() {
            return new Type[]{Integer.class, String.class};
        }

        public Type getRawType() {
            return Hashtable.class;
        }

        public Type getOwnerType() {
            return null;
        }
    };
	
	public UpdateFriendList(int useraccount,DataInputStream inputStream,DataOutputStream outputStream) {
		this.useraccount = useraccount;
		this.input = inputStream;
		this.output = outputStream;
				
	}
		
	public void getMessage() {
		
		try {
			System.out.println("running1");
			String json = input.readUTF();
			Gson gson = new Gson();
			Message mes = gson.fromJson(json, Message.class);
			if(mes.getType() == MsgType.UPDATE_FRIENDLIST) {
				System.out.println("更新friendlist");
				FriendList fl = FriendListManager.getFriendListFrame(useraccount);
				this.updatefl(fl,mes);
			}else if(mes.getType() == MsgType.ADD_MESSAGE) {
				Hashtable<Integer, String> addMessages = new Hashtable<Integer, String>();
				addMessages = gson.fromJson(mes.getText(), hashtableType);
				addmes = addMessages;
				if(!addMessages.isEmpty()) {
					Platform.runLater(() -> {
                        Alert alert = new Alert(Alert.AlertType.INFORMATION);
                        alert.setTitle("提示");
                        alert.setContentText("您有新的好友申请，请及时查看");
                        alert.showAndWait();
                        return;
                    });
				}
			}
			
		}catch (IOException e) {
			isrunning = false;
			s.closeall(input,output);
		}

	}
	
	public void updatefl(FriendList fl,Message mes) {
		
		fl.updateOnlineFriends(mes);
	}
	
	public Hashtable<Integer, String> getMsg() {
		return addmes;
	}
	
	public void run() {
		while(isrunning) {
			this.getMessage();		
		}
	}
		
}